import React, { useState } from 'react';
import {
  Card,
  Button,
  Input,
  Typography,
  Descriptions,
  Table,
  Tag,
  Modal,
  Form,
  InputNumber,
  message,
  Col,
  Row,
  Empty,
  Spin,
} from 'antd';
import { UserOutlined, SearchOutlined, SyncOutlined, PieChartOutlined } from '@ant-design/icons';

const { Title, Paragraph } = Typography;
const { Search } = Input;

// Mock database of clients and their holdings
const mockClientData = {
  'CUST-113': {
    name: '赵先生',
    id: 'CUST-113',
    riskLevel: '平衡型',
    standardPortfolio: '大类资产轮动',
    holdings: [
      { key: '1', fundName: '广发纳斯达克100ETF', currentWeight: 55, targetWeight: 40 },
      { key: '2', fundName: '易方达沪深300ETF', currentWeight: 30, targetWeight: 40 },
      { key: '3', fundName: '华安黄金ETF', currentWeight: 15, targetWeight: 20 },
    ],
  },
  'CUST-088': {
    name: '孙女士',
    id: 'CUST-088',
    riskLevel: '保守型',
    standardPortfolio: '稳健增长FOF组合',
    holdings: [
      { key: '1', fundName: '华夏成长混合', currentWeight: 20, targetWeight: 25 },
      { key: '2', fundName: '易方达消费行业', currentWeight: 45, targetWeight: 35 },
      { key: '3', fundName: '广发稳健增长', currentWeight: 35, targetWeight: 40 },
    ],
  },
};

const STORAGE_KEY = 'accountRebalanceClients';

const AccountRebalance = () => {
  // 页面加载时从localStorage读取所有客户数据
  const local = localStorage.getItem(STORAGE_KEY);
  const [clientData, setClientData] = useState(local ? JSON.parse(local) : mockClientData);
  const [searchedClient, setSearchedClient] = useState(null);
  const [loading, setLoading] = useState(false);
  const [isModalVisible, setIsModalVisible] = useState(false);
  const [form] = Form.useForm();
  
  const handleSearch = (clientId) => {
    setLoading(true);
    setSearchedClient(null);
    setTimeout(() => {
      const client = clientData[clientId.toUpperCase()];
      if (client) {
        setSearchedClient(client);
        form.setFieldsValue({
            holdings: client.holdings.map(h => ({ ...h, newWeight: h.targetWeight }))
        });
      } else {
        message.error('未找到该客户账号');
      }
      setLoading(false);
    }, 1000);
  };
  
  const handleRebalanceSubmit = (values) => {
    message.loading({ content: '正在生成独立调仓指令...', key: 'accountRebalance' });
    setTimeout(() => {
      // 更新本地数据
      const updated = { ...searchedClient, holdings: values.holdings.map(h => ({ ...h, currentWeight: h.newWeight })) };
      const newClientData = { ...clientData, [searchedClient.id]: updated };
      setClientData(newClientData);
      localStorage.setItem(STORAGE_KEY, JSON.stringify(newClientData));
      message.success({ content: `客户 ${searchedClient.name} 的调仓指令已下发!`, key: 'accountRebalance' });
      setIsModalVisible(false);
    }, 1500);
  };

  const columns = [
    { title: '基金名称', dataIndex: 'fundName', key: 'fundName' },
    { title: '当前持仓权重(%)', dataIndex: 'currentWeight', key: 'currentWeight', render: (w) => `${w}%` },
    { title: '标准组合权重(%)', dataIndex: 'targetWeight', key: 'targetWeight', render: (w) => `${w}%` },
    { 
      title: '偏离度', 
      key: 'deviation',
      render: (_, record) => {
        const deviation = record.currentWeight - record.targetWeight;
        const color = deviation > 2 ? 'red' : deviation < -2 ? 'green' : 'default';
        const sign = deviation > 0 ? '+' : '';
        return <Tag color={color}>{`${sign}${deviation.toFixed(1)}%`}</Tag>
      }
    },
  ];

  return (
    <div style={{ padding: '24px' }}>
      <Title level={3}>账户调仓</Title>
      <Paragraph type="secondary">
        当客户持仓与标准组合差异较大时，可在此为客户独立进行持仓查询和组合调仓。
      </Paragraph>

      <Card style={{ marginBottom: 24 }}>
        <Search
          placeholder="请输入客户财富账号进行查询"
          enterButton={<><SearchOutlined /> 查询</>}
          size="large"
          onSearch={handleSearch}
          loading={loading}
        />
      </Card>

      <Spin spinning={loading}>
        {searchedClient ? (
          <Card>
            <Descriptions title="客户持仓详情" bordered>
              <Descriptions.Item label="客户姓名">{searchedClient.name}</Descriptions.Item>
              <Descriptions.Item label="客户账号">{searchedClient.id}</Descriptions.Item>
              <Descriptions.Item label="风险等级">{searchedClient.riskLevel}</Descriptions.Item>
              <Descriptions.Item label="当前订阅组合">{searchedClient.standardPortfolio}</Descriptions.Item>
            </Descriptions>
            <Table
              columns={columns}
              dataSource={searchedClient.holdings}
              pagination={false}
              style={{ marginTop: 24 }}
            />
             <div style={{textAlign: 'right', marginTop: 16}}>
                <Button type="primary" icon={<SyncOutlined />} onClick={() => setIsModalVisible(true)}>
                    发起独立调仓
                </Button>
            </div>
          </Card>
        ) : (
          <Empty description="请输入客户账号以查询持仓详情" />
        )}
      </Spin>
      
      <Modal
        title={
            <div style={{display: 'flex', alignItems: 'center'}}>
                <PieChartOutlined style={{marginRight: 8}}/>
                <span>独立调仓计划</span>
            </div>
        }
        open={isModalVisible}
        onCancel={() => setIsModalVisible(false)}
        width={600}
        footer={null}
      >
        {searchedClient && (
            <Form form={form} layout="vertical" onFinish={handleRebalanceSubmit}>
                <Paragraph>正在为客户 <strong>{searchedClient.name}</strong> ({searchedClient.id}) 创建独立调仓计划。</Paragraph>
                <Form.List name="holdings">
                    {(fields) => (
                        <>
                        {fields.map(({ key, name, ...restField }, index) => (
                             <Row key={key} gutter={16} align="middle">
                                <Col span={12}>
                                    <Form.Item
                                        {...restField}
                                        name={[name, 'fundName']}
                                    >
                                        <Input bordered={false} readOnly/>
                                    </Form.Item>
                                </Col>
                                <Col span={12}>
                                    <Form.Item
                                        {...restField}
                                        name={[name, 'newWeight']}
                                        label={`新目标权重(%)`}
                                        rules={[{ required: true, message: '请输入权重' }]}
                                    >
                                        <InputNumber min={0} max={100} style={{width: '100%'}} />
                                    </Form.Item>
                                </Col>
                            </Row>
                        ))}
                        </>
                    )}
                </Form.List>
                <Form.Item style={{ textAlign: 'right', marginTop: 24, marginBottom: 0 }}>
                    <Button onClick={() => setIsModalVisible(false)} style={{ marginRight: 8 }}>
                        取消
                    </Button>
                    <Button type="primary" htmlType="submit">
                        提交独立调仓计划
                    </Button>
                </Form.Item>
            </Form>
        )}
      </Modal>
    </div>
  );
};

export default AccountRebalance; 